<?php

namespace app\api\controller;

use app\api\extend\Common;
use think\facade\Db;

class HomeExchanmall extends Common
{
    public function list() {
        $result = [];
        $res = $this->model->list();
        $classif = Db::name('home_comclassif')->select();

        foreach ($res as $v1) {
           foreach ($classif as $k2 => $v2) {
                  if ($v2['id'] == $v1['classif_goods_id']) {
                     if (!isset($result[$k2])) {
                          $result[$k2] = ['classif_id'=>$v2['id'],'classif_name'=>$v2['name']];
                     }
                      $result[$k2]['list'][] = [
                        'id'=>$v1['id'],
                        'title'=>$v1['name'],
                        'price'=>$v1['price'],
                        'pic_image'=>$v1['pic_image'],
                      ];
                  }
              }   
        }
        return $this->return_msg(200,'获取成功',$result);
    }

    public function shop(){
        $totalAmount = $this->params['totalAmount'];
        $user = Db::name('home_muser')->where('id' , $this->request->auth['userId'])->find();
        if (empty($user) || $user['exchan_coin'] <  $totalAmount) {
            return $this->return_msg(400,'余额不足');
        }

        $res = Db::name('home_muser')->where('id' , $this->request->auth['userId'])
        ->update([
            'exchan_coin' => $user['exchan_coin'] -=  $totalAmount
        ]);
        if (!$res) {
           return $this->return_msg(500,'更新余额失败');
        }

         // 保存订单信息
        $res = Db::name('home_excorder')->save([
            'muser_id' => $this->request->auth['userId'],
            'amount' => $totalAmount,
            'exc_id' => $this->params['exc_id'],
            'status' => 1, // 假设订单状态为已支付
        ]);
        
        // 其他订单信息...
 
        if (empty($res)) {
            // 如果订单保存失败，回滚余额操作
            $user['exchan_coin'] +=  $totalAmount;
            Db::name('home_muser')->where('id' , $this->request->auth['userId'])
            ->update([
                'exchan_coin' => $user['exchan_coin'] -=  $totalAmount
            ]);
            return $this->return_msg(500,'保存订单失败');
        }

         return $this->return_msg(200,'保存订单成功');
    }

    public function history()
    {
        $where = [
            ['a.muser_id' , '=' , $this->request->auth['userId']],
        ];
        $res = Db::name('home_order')
        ->alias('a')
        ->join('home_exchanmall b','b.id = a.exc_id')
        ->where($where)
        ->select();

        if (empty($res)) {
            return $this->return_msg(400,'获取失败');
        }
        return $this->return_msg(200,'获取成功',$res);

    }
}